package com.xqkad.myplayer.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.text.SimpleDateFormat;

public class PreferencesUtility {
    public static final String SERVICE_CREATE_TIME = "SERVICE_CREATE_TIME";
    public static final String SERVICE_DESTROY_TIME = "SERVICE_DESTROY_TIME";
    public static final String SERVICE_LIFE_TIME = "SERVICE_LIFE_TIME";

    private static PreferencesUtility sInstance;
    private SharedPreferences mPreferences;

    private PreferencesUtility(Context context){
        this.mPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    }

    public static PreferencesUtility getInstance(Context context){
        if(sInstance == null)
            sInstance = new PreferencesUtility(context);
        return sInstance;
    }

    public String get(String key){
        return mPreferences.getString(key,"0");
    }

    public void set(String key, Object value){
        SharedPreferences.Editor edit = mPreferences.edit();
        edit.putString(key,""+value);
        edit.commit();
    }

    public static void setServiceCreateTime(Context context){
        getInstance(context).set(SERVICE_CREATE_TIME, System.currentTimeMillis());
    }

    public static String getServiceCreateTime(Context context){
        return getInstance(context).get(SERVICE_CREATE_TIME);
    }

    public static void setServiceDestroyTime(Context context){
        getInstance(context).set(SERVICE_DESTROY_TIME, System.currentTimeMillis());
    }

    public static String getServiceDestroyTime(Context context){
        return getInstance(context).get(SERVICE_DESTROY_TIME);
    }

    public static void setServiceLifeTime(final Context context){
        getInstance(context).set(SERVICE_LIFE_TIME, System.currentTimeMillis() - Long.valueOf(getServiceCreateTime(context)));
    }

    public static String getServiceLifeTime(Context context){
        return getInstance(context).get(SERVICE_LIFE_TIME);
    }

    public static String makeTimeString2(long millis) {
        //1小时1分05秒
        StringBuffer sb = new StringBuffer();

        long h = millis / (60 * 60 * 1000);
        if(h > 0){
            sb.append(h+"小时");
        }

        long m = (millis % (60 * 60 * 1000)) / (60 * 1000);
        if(m > 0){
            sb.append(m+"分");
        }
        //sb.append(":");
        long s = (millis % (60 * 1000)) / 1000;
        sb.append(s < 10 ? "0" + s : s);
        sb.append("秒");
        return sb.toString();
    }
}
